﻿#include "ClientDataRecordSqlTableModel.h"
#include <QDebug>
#include <QSqlQuery>
#include <QSqlError>

static const QString ClientDataRecordTableName = "clientDataRecordInfo";

ClientDataRecordSqlTableModel::ClientDataRecordSqlTableModel()
{
    createTable();
     //只有提交才能生效到数据库   submitAll();
    setEditStrategy(OnManualSubmit);
    setTable(ClientDataRecordTableName);
    //从数据库里把所有数据读到Model 也就是把本地数据库的文件读到C++内存里
    select();
    set_count(rowCount());
    submitAll();
    //服务器刚打开，所有客户端都应该断开连接
    initStatus();
}

QHash<int, QByteArray> ClientDataRecordSqlTableModel::roleNames() const
{
    QHash<int, QByteArray> names;
    names[AccountNumber] = "accountNumber";
    names[Password]      = "password";
    names[UserState]     = "userState";
    names[ErrorTimes]     = "errorTimes";
    names[RegistrationDate] = "registrationDate";
    return names;
}

QVariant ClientDataRecordSqlTableModel::data(const QModelIndex &index, int role) const
{
    //满足这个条件一般是初始化的时候
    if (role < Qt::UserRole)
        return QSqlTableModel::data(index, role);
    //到这里一般是qml哪里来拿数据
    const QSqlRecord sqlRecord = record(index.row());//行
    int valueId = role - AccountNumber;//列
    qDebug () << "value = " << valueId << "real v =" << sqlRecord.value(valueId);
    return QVariant(sqlRecord.value(valueId));//获取到的数据
}

void ClientDataRecordSqlTableModel::insertAccount(const QString &account, const QString &password)
{

    int rowNum = rowCount();
    //插入一行空的
    insertRow(rowNum);
    setData(index(rowNum, 0), account);
    setData(index(rowNum, 1), password);
    setData(index(rowNum, 2), 0);
    setData(index(rowNum, 3), 0);
    QString time = QDateTime::currentDateTime().toString ("yyyy-MM-dd hh:mm:ss");
    setData(index(rowNum, 4), time);
    submitAll();
    set_count(rowCount());
}

bool ClientDataRecordSqlTableModel::accountIsInModel(const QString &count, int& index)
{
    int countRow = rowCount();
    for(int i = 0; i< countRow; i++) {
        //找到一样的
        if(count == getData(i, AccountNumber).toString()) {
            index = i;
            return true;
        }
    }
    return false;
}

void ClientDataRecordSqlTableModel::removeARow(int row) {
    removeRow(row);
    submitAll();
}

QVariant ClientDataRecordSqlTableModel::getData(int row, int role) {
    //到这里一般是qml哪里来拿数据
    const QSqlRecord sqlRecord = record(row);//行
    int valueId = role - AccountNumber;//列
    return QVariant(sqlRecord.value(valueId));//获取到的数据
}

void ClientDataRecordSqlTableModel::modifyData(int row, int role, QString tex)
{
    //有时候role可能是ClientDataEnum
    if(role >= Qt::UserRole) {
        setData(index(row, role - AccountNumber), tex);
    }else {
        setData(index(row, role), tex);
    }
}

void ClientDataRecordSqlTableModel::createTable()
{
    //判断数据库里有没有这张表
    if (QSqlDatabase::database().tables().contains(ClientDataRecordTableName)) {
        // The table already exists; we don't need to do anything.
        return;
    }
    qDebug() << "table not exist";
    QSqlQuery query;
    QString sql_ = QStringLiteral("CREATE TABLE IF NOT EXISTS [%1] ( \
                                  [accountNumber]  VARCHAR2, \
                                  [password] VARCHAR2 , \
                                  [userState] VARCHAR2,\
                                  [errorTimes] VARCHAR2, \
                                  [registrationDate] VARCHAR2);").arg(ClientDataRecordTableName);
    //执行创建数据库的同时判断是否成功
    if (!query.exec(sql_)) {
        qFatal("Failed to query database: %s", qPrintable(query.lastError().text()));
    }
}

void ClientDataRecordSqlTableModel::initStatus()
{
    for(int i = 0 ; i < rowCount(); i++) {
        modifyData(i, UserState, "0");
    }
}

